package com.example.myspringboot.test;

import lombok.SneakyThrows;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ZkClient {

    //对应的zookeeper客户端连接,连接之间不能存在空格  例如：192.168.154.133:2181,192.168.154.134:2181,192.168.154.135:2181
    private String connectString = "123.249.37.216:2181";
    //即超时时间，我们设置成2s
    private int sessionTimeout = 2000;
    //声明zookeeper客户端
    ZooKeeper zookeeper = null;


    //初始化
    @Test
    public void init() throws IOException {
        try {
            zookeeper = new ZooKeeper(connectString, sessionTimeout, event -> {});
            if (zookeeper.getState().isAlive()) {
                System.out.println("Zookeeper is running.");
            } else {
                System.out.println("Zookeeper is not running.");
            }
        } catch (Exception e) {
            System.out.println("Zookeeper is not running.");
        } finally {
            try {
                if (zookeeper != null) {
                    zookeeper.close();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    static ZooKeeper zooKeeper = null;
    private static final String ADDRESS = "123.249.37.216:2181";

    @Test
    public void testMain() throws Exception {
        zooKeeper = new ZooKeeper(ADDRESS, 10000, new Watcher() {
            @SneakyThrows
            @Override
            public void process(WatchedEvent event) {
                Event.EventType type = event.getType();
                Event.KeeperState state = event.getState();
                System.out.println(type);
                System.out.println(state);

                if (type == Event.EventType.None && state == Event.KeeperState.SyncConnected) {
                    System.out.println("连接上了");
                } else if (type == Event.EventType.NodeCreated && state == Event.KeeperState.SyncConnected) {
                    System.err.println("子节点数量发生变化" + event.getPath());
                    try {
                        List<String> children = zooKeeper.getChildren("/zstest", true);
                        System.err.println(children);
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                countDownLatch.countDown();//放行

            }
        });

        countDownLatch.await();
        System.out.println("开始执行");

        // 创建节点
        zooKeeper.exists("/zstest",true);
        zooKeeper.create("/zstest","hello,world".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);

        // 获取数据
        byte[] data = zooKeeper.getData("/zstest", true, null);
        System.out.println(new String(data));

        // 修改数据 最后的版本号的目的是乐观锁,如果忽略乐观锁写-1,否则必须匹配当前数据的版本号
        Stat stat = zooKeeper.setData("/zstest", "11111111111111111".getBytes(), -1);
        System.out.println(stat);

        // 删除
        zooKeeper.delete("/zstest",-1);

//        // 创建子节点
//        List<String> children = zooKeeper.getChildren("/hzx2005", true);
//        System.out.println(children);
//        zooKeeper.create("/zstest/day20200917", "饭卡里你发来看".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
//
//        for (String child : children) {
//            byte[] data = zooKeeper.getData("/sh2005/" + child, true, null);
//            System.err.println(new String(data));
//        }
//        //不允许在父节点不存在的情况下创建子节点
//        zooKeeper.create("/dasdasd/dasdasdas/dasdasd", "大叔大婶大所多".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);


        System.in.read();
    }



}
